<template>
    <div class="madp-customer-label">
        <basic-container>
            <div class="madp-top">
                <div>
                    <el-button v-if="permissions.cp_customer_label_add" type="primary" icon="el-icon-plus" @click="rowForm">新建标签组</el-button>
                </div>
                <p v-if="synTime">最后一次同步时间:{{ synTime }}</p>
            </div>
            <!-- 表格 -->
            <el-table
                :header-cell-style="{
                    background: 'rgb(255, 191, 191)',
                    color: 'rgb(44,44,44)'
                }"
                stripe
                :data="tableData"
                v-loading="loading"
            >
                <el-table-column label="序号" width="60" type="index">
                    <template slot-scope="scope">
                        <span v-text="getIndex(scope.$index)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="标签类型" width="100">
                    <template slot-scope="scope">{{ scope.row.type === '0' ? '企业标签' : '系统标签' }}</template>
                </el-table-column>
                <el-table-column prop="groupName" label="标签组" width="140"></el-table-column>
                <el-table-column label="标签">
                    <template slot-scope="scope">
                        <el-tag class="madp-column-tag" v-for="(item, index) in scope.row.tagNameList" :key="index">{{ item }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createName" label="创建人" width="120"></el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button type="text" @click.native.prevent="seeForm(scope.$index, scope.row)">查看</el-button>
                        <el-button v-if="scope.row.type == '0' && permissions.cp_customer_label_edit" type="text" @click.native.prevent="rowForm(scope.$index, tableData)">编辑</el-button>
                        <el-button v-if="scope.row.type == '0' && permissions.cp_customer_label_del" type="text" @click.native.prevent="deleteRow(scope.$index, tableData)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                background
                class="madp-pagination"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.current"
                :page-sizes="[10, 20, 30, 50, 100]"
                :page-size="page.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
            ></el-pagination>

            <!-- 新建/编辑标签 弹框 -->
            <el-dialog :title="updateForm.tittle" :visible.sync="dialogUpdateGroup" :before-close="handleCancel" :close-on-click-modal="false">
                <el-form :model="updateForm" :rules="rules" ref="updateForm" label-width="120px">
                    <el-form-item label="标签组名称" prop="groupName">
                        <el-input
                            placeholder="请输入标签组名称，该名称不支持再次修改"
                            v-model.trim="updateForm.groupName"
                            :onkeyup="(updateForm.groupName = updateForm.groupName.replace(/\s+/g, ''))"
                            maxlength="30"
                            autocomplete="off"
                            :disabled="updateForm.tittle === '编辑标签' ? true : false"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="标签" class="madp-label-item" required>
                        <el-input
                            placeholder="请输入标签名，按回车完成，多个标签用‘，’（中文）隔开"
                            v-model.trim="updateForm.addTagName"
                            @input="updateInput"
                            @keyup.enter.native="handleInputConfirm"
                        ></el-input>
                        <div v-if="updateForm.tagNameList[0]">
                            <el-tag v-for="(tag, index) in updateForm.tagNameList" class="madp-column-tag" :key="index" closable :disable-transitions="false" @close="handleClose(tag)">{{
                                tag
                            }}</el-tag>
                        </div>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确定</el-button>
                </div>
            </el-dialog>
            <!-- 查看弹窗 -->
            <el-dialog title="查看标签" :visible.sync="seeDialog" :close-on-click-modal="false">
                <p class="madp-check-label">标签组名称:{{ groupName }}</p>
                <el-table
                    :header-cell-style="{
                        background: 'rgb(255, 191, 191)',
                        color: 'rgb(44,44,44)'
                    }"
                    :data="seeData"
                    border
                    stripe
                    v-loading="dialogloading"
                >
                    <el-table-column type="index" label="序号" width="150" align="center"></el-table-column>
                    <el-table-column property="name" label="标签名称" width="200" align="center"></el-table-column>
                    <el-table-column property="contactNum" label="客户数" align="center"></el-table-column>
                </el-table>
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
import { getCustomerLabelList, addLabelGroup, editLabelGroup, deleteLabel, watchRowList } from '@/api/customer/customer-label';
import { mapGetters } from 'vuex';
export default {
    name: 'madp-customer-label',
    data() {
        let validateTag = (rule, value, callback) => {
            if (this.updateForm.tagNameList.length === 0) {
                callback(new Error('请添加标签'));
            } else {
                callback();
            }
        };
        return {
            // 组名
            groupName: '',
            // loading开关
            loading: false,
            synTime: '', // 最后一次同步时间
            // 更新表单内容
            updateForm: {
                tittle: '添加标签',
                groupName: '',
                tagNameList: [],
                addTagName: ''
            },
            primaryIsHide: true,
            openInput: false,
            seeDialog: false, // 弹窗开关
            seeData: [], // 表格数据
            tempTagNameList: [], // tag名组
            // 表单校验规则
            rules: {
                groupName: [
                    {
                        required: true,
                        message: '请输入标签组名称',
                        trigger: 'blur'
                    }
                ]
            },
            // 弹窗开关
            dialogUpdateGroup: false,
            // 表格数据
            tableData: [],
            // 分页
            page: {
                total: 0,
                current: 1,
                size: 10
            },
            // 弹窗loading开关
            dialogloading: false
        };
    },
    created() {},
    mounted() {
        this.getTableList();
    },
    computed: {
        ...mapGetters(['permissions'])
    },
    methods: {
        //获取表格序号
        getIndex($index) {
            return (this.page.current - 1) * this.page.size + $index + 1;
        },
        // 更新输入内容
        updateInput() {
            let str = this.updateForm.addTagName;
            str = str.replace(/\s+/g, '');
            let arr = str.split('，');
            arr = arr.map((i) => {
                if (i.length > 30) {
                    i = i.slice(0, 30);
                }
                return i;
            });
            this.updateForm.addTagName = arr.join('，');
        },
        // 获取表格数据
        getTableList() {
            this.loading = true;
            const { current, size } = this.page;
            let obj = {
                current: current,
                size: size
            };
            getCustomerLabelList(obj)
                .then((res) => {
                    if (res.data.code === 0) {
                        const { records, total } = res.data.data;
                        this.synTime = res.data.data.extraProps.syncTagTime;
                        this.tableData = records;
                        this.page.total = total;
                    }
                    this.loading = false;
                })
                .catch((err) => {
                    this.loading = false;
                });
        },
        // 删除
        deleteRow(index, data) {
            this.$confirm('确认是否删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    deleteLabel(data[index].groupId).then((res) => {
                        if (res.data && res.data.data && res.data.code === 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getTableList();
                        }
                    });
                })
                .catch(() => {});
        },
        // 查看详情
        seeForm(index, row) {
            this.seeDialog = true;
            this.seeData = [];
            this.groupName = row.groupName;
            this.dialogloading = true;
            watchRowList(row.groupId)
                .then((res) => {
                    this.dialogloading = false;
                    if (res.data && res.data.code === 0 && res.data.data) {
                        this.seeData = res.data.data.records;
                    }
                })
                .catch((err) => {
                    this.dialogloading = false;
                });
        },
        // 编辑
        rowForm(index, row) {
            if (row) {
                this.updateForm = JSON.parse(JSON.stringify(row[index]));
                this.tempTagNameList = JSON.parse(JSON.stringify(this.updateForm.tagNameList));
                this.updateForm.tittle = '编辑标签';
            } else {
                this.updateForm = {
                    tittle: '添加标签',
                    groupName: '',
                    tagNameList: [],
                    addTagName: ''
                };
            }
            this.dialogUpdateGroup = true;
        },
        // 编辑和新建的弹框中的确认按钮
        handleConfirm() {
            if (this.updateForm.tittle === '编辑标签') {
                this.handleInputConfirm();
                let { groupId, tagNameList } = this.updateForm;
                let obj = {
                    groupId,
                    tagNameList
                };
                editLabelGroup(obj).then((res) => {
                    if (res.data.code === 0) {
                        this.$message({
                            type: 'success',
                            message: '编辑成功'
                        });
                        this.getTableList();
                        this.dialogUpdateGroup = false;
                    }
                });
            } else {
                this.$refs['updateForm'].validate((valid) => {
                    if (valid) {
                        this.handleInputConfirm();
                        const { groupName, tagNameList } = this.updateForm;
                        addLabelGroup({
                            groupName,
                            tagNameList
                        })
                            .then((res) => {
                                if (res.data.code === 0) {
                                    if (res.data.data === '标签组已存在') {
                                        this.$message({
                                            type: 'error',
                                            message: '标签组已存在'
                                        });
                                    } else {
                                        this.$message({
                                            type: 'success',
                                            message: '添加成功'
                                        });
                                        this.getTableList();
                                        this.dialogUpdateGroup = false;
                                    }
                                }
                            })
                            .catch((err) => {});
                    } else {
                        return false;
                    }
                });
            }
        },
        // 编辑和新建的弹框中的取消按钮
        handleCancel() {
            this.$refs['updateForm'].resetFields();
            this.dialogUpdateGroup = false;
            if (this.updateForm.tittle === '编辑标签') {
                this.updateForm.tagNameList = JSON.parse(JSON.stringify(this.tempTagNameList));
            }
        },
        // 处理input框添加标签
        handleInputConfirm() {
            let _this = this;
            if (_this.updateForm.addTagName) {
                let inputValue = _this.updateForm.addTagName.split('，');
                inputValue.map(function(currentValue, index, arr) {
                    if (!currentValue.trim() == '' && _this.updateForm.tagNameList.indexOf(currentValue) < 0) {
                        _this.updateForm.tagNameList.push(currentValue);
                    }
                });
                this.updateForm.addTagName = '';
            }
        },
        // 删除单个标签
        handleClose(tag) {
            this.updateForm.tagNameList.splice(this.updateForm.tagNameList.indexOf(tag), 1);
        },
        // 分页
        handleSizeChange(val) {
            this.page.size = val;
            this.page.current = 1;
            this.getTableList();
        },
        // 分页
        handleCurrentChange(val) {
            this.page.current = val;
            this.getTableList();
        }
    }
};
</script>

<style lang="scss" scoped>
.madp-customer-label {
    .madp-labelbox {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
    }
    .madp-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        margin-bottom: 20px;
    }
    .madp-pagination {
        float: right;
        margin-top: 20px;
        margin-bottom: 20px;
    }
}
.madp-label-item {
    .madp-column-tag {
        margin: 10px 8px 0 0;
    }
}
.madp-column-tag {
    margin: 2.5px 5px 2.5px 0;
}
.madp-check-label {
    margin-top: -20px !important;
    margin-bottom: 20px !important;
}
</style>
